package com.eltonkent.dashboard.service.responsehandler;

import java.io.IOException;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.eltonkent.dashboard.data.container.WeatherContainer;
import com.eltonkent.dashboard.util.logger.Logger;

public final class GoogleWeatherHandler extends XmlHandler {

	private static final String NODE_PROBLEM = "problem_cause";
	private static final String NODE_TEMP_FAREN = "temp_f";
	private static final String NODE_TEMP_CENTI = "temp_c";
	private static final String NODE_HUMIDITY = "humidity";
	private static final String NODE_WIND_CONDITIONS = "wind_condition";
	private static final String NODE_CONDITIONS = "condition";

	@Override
	public WeatherContainer deserialize(InputStream is) {
		try {
			Logger.d("DBA","[GoogleWeatherResponse] Starting xml processing");
			XmlPullParser parser = getParser(is);
			WeatherContainer container = new WeatherContainer();
			container.setGoogleResponse(true);
			int eventType = parser.getEventType();
			String tagName;
			for (; eventType != XmlPullParser.END_DOCUMENT;) {
				if (eventType == XmlPullParser.START_TAG) {
					tagName = parser.getName();
					if (tagName.equals(NODE_PROBLEM)) {
						container.setValidResponse(false);
					} else if (tagName.equals(NODE_TEMP_FAREN)) {
						container.setTempInFaren(parser.getAttributeValue(0));
					} else if (tagName.equals(NODE_TEMP_CENTI)) {
						container.setTempInCelcius(parser.getAttributeValue(0));
					} else if (tagName.equals(NODE_HUMIDITY)) {
						container
								.setGoogleHumidity(parser.getAttributeValue(0));
					} else if (tagName.equals(NODE_WIND_CONDITIONS)) {
						container.setGoogleWindCondition(parser.getAttributeValue(0));
						break;
					} else if (tagName.equals(NODE_CONDITIONS)) {
						container.setWeatherCondition(parser
								.getAttributeValue(0));
					}
				}
				eventType = parser.next();
			}
			is.close();
			Logger.d("DBA","[GoogleWeatherResponse]"+container.toString());
			return container;
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
